package com.ga.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.alibaba.fastjson.JSON;
import com.ga.model.Album;
import com.ga.model.User;
import com.ga.service.UploadService;
import com.ga.util.Algo;
import com.ga.util.Common;
import com.ga.util.MessageUtil;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.oreilly.servlet.MultipartRequest;

public class UsersController extends Controller {

	public void index() {
		render("user/home.html");
	}
	@ActionKey("/user/avatar")
	public void avatar(){
		  Map<String,String> m=new HashMap<String,String>();
		  try{
			int maxFileSize =1024*1024*1; //1M
			int maxMemSize = 1024*1024*1; //1M
			String filePath = this.getRequest().getRealPath("")+"\\resources\\avatar\\";
			String uname=getPara("uname");
			String contentType = this.getRequest().getContentType();
			if ((contentType.indexOf("multipart/form-data") >= 0)) {
				String fileName=UploadService.instance.upload(maxMemSize, maxFileSize, uname, filePath, this.getRequest());
				m.put("imgsrc", "\\resources\\avatar\\"+fileName);
			}
		} catch (Exception e) {
			m.put("imgsrc", "");
			e.printStackTrace();
		}
		 renderJson(m);
	}

	@ActionKey("/user/login")
	public void login() {
		Object[] obj = { getPara("uname"), getPara("pwd") };
		User user = User.dao.findFirst("select * from users where uname= ?  and pwd = ? ", obj);
		Map<String, Object> map = new HashMap<String, Object>();
		if (user!=null) {
			map.put("flag", MessageUtil.SUCCESS.toString());
			map.put("pwd", Algo.encrypt(getPara("pwd")));
			this.setSessionAttr("user", user);
		} else
			map.put("flag", MessageUtil.FAILED.toString());
		renderJson(map);
	}
	@ActionKey("/user/logout")
	public void logout() {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			this.removeSessionAttr("user");
			map.put("flag", MessageUtil.SUCCESS.toString());
		} catch (Exception e) {
			map.put("flag", MessageUtil.FAILED.toString());
			e.printStackTrace();
		}
		renderJson(map);
	}
	@ActionKey("/user/resetpwd")
	public void resetpwd(){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			
			String id=getPara(0);
			Db.update("update users set pwd=111111 where id= ?" ,id);
			map.put("flag", MessageUtil.SUCCESS.toString());
		} catch (Exception e) {
			map.put("flag", MessageUtil.FAILED.toString());
			e.printStackTrace();
		}
		renderJson(map);
	}

	@ActionKey("/user/register/save")
	public void registersave() {
		User user = User.dao.findFirst("select count(1) as c from users where uname=?", getPara("uname"));
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (null == getPara("uname")) {
				map.put("flag", MessageUtil.FAILED.toString());
				map.put("msg", "用户名不能为空 !");
			} else if (Integer.parseInt(user.get("c").toString()) > 0) {
				map.put("flag", MessageUtil.FAILED.toString());
				map.put("msg", "该用户已注册 !");
			} else {
				new User().set("uname", getPara("uname")).set("pwd", getPara("pwd")).set("lastmodifytime", new Date()).save();
				map.put("flag", MessageUtil.SUCCESS.toString());
			}
		} catch (NumberFormatException e) {
			map.put("flag", MessageUtil.FAILED.toString());
			e.printStackTrace();
		}
		renderJson(map);
	}

	@ActionKey("/user/update/save")
	public void updatesave() {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			User user = new User();
			user.set("uname", getPara("uname"));
			user.set("nickname", getPara("nickname"));
			user.set("avatar", getPara("avatar"));
			user.set("sex", getPara("sex"));
			user.set("question", getPara("question"));
			user.set("answer", getPara("answer"));
			user.set("description", getPara("description"));
			user.set("active", getPara("active"));
			user.set("channel", getPara("channel"));
			user.set("lastmodifytime", new Date());
			user.set("id", getPara("id"));
			if (user.update())
				map.put("flag", MessageUtil.SUCCESS.toString());
			else
				map.put("flag", MessageUtil.FAILED.toString());
		} catch (Exception e) {
			map.put("flag", MessageUtil.FAILED.toString());
			e.printStackTrace();
		}
		renderJson(map);
	}

	@ActionKey("/user/detail")
	public void info() {
		Map<String, Object> map = new HashMap<String, Object>();
		String sql="select *,"+Common.usercase()+" from users where id=?";
		User user = User.dao.findFirst(sql,getPara("id"));
		if (user == null) {
			map.put("flag", MessageUtil.FAILED.toString());
			map.put("msg", "该用户不存在 !");
		} else {
			map.put("flag", MessageUtil.SUCCESS.toString());
			map.put("user", user);
		}
		renderJson(map);
	}

	@ActionKey("/user/isexistsuname")
	public void isexistsuname() {
		Map<String, Object> map = new HashMap<String, Object>();
		User user = User.dao.findFirst("select count(1) as c from users where uname=?", getPara("uname"));
		if (Integer.parseInt(user.get("c").toString()) > 0) {
			map.put("flag", MessageUtil.FAILED.toString());
			map.put("msg", "该用户名已存在 !");
		} else {
			map.put("flag", MessageUtil.SUCCESS.toString());
			map.put("msg", "该用户名可用 !");
		}
		renderJson(map);
	}

	@ActionKey("/user/list")
	public void list() {
		Page<User> list=new Page<User>(null, 0, 0, 0, 0);
		try {
			Map<String,Object> paraMap=new HashMap<String,Object>();
			paraMap.put("isenable", 1);
			paraMap.put("uname", getPara("uname"));
			paraMap.put("nickname", getPara("nickname"));
			paraMap.put("sex=", getPara("sex"));
			paraMap.put("active=", getPara("active"));
			paraMap.put("channel=", getPara("channel"));
			paraMap.put("description", getPara("description"));
			paraMap.put("createtime1", getPara("createtime1"));
			paraMap.put("createtime2", getPara("createtime2"));
			paraMap.put("lastmodifytime1", getPara("lastmodifytime1"));
			paraMap.put("lastmodifytime2", getPara("lastmodifytime2"));
			Map<String,Object> wheresMap=Common.wheres(paraMap);
			int pn = Integer.parseInt(getPara("pageNumber")==null?"1":getPara("pageNumber"));
			int ps = Integer.parseInt(getPara("pageSize")==null?"10":getPara("pageSize"));	
			Object[] param=(Object[]) wheresMap.get("param");
			String sql="select id,uname,nickname,avatar,createtime,lastmodifytime,"+Common.usercase();
			list = User.dao.paginate(pn, ps, sql, " from users where "+wheresMap.get("wheres"), param);
		} catch (Exception e) {
			e.printStackTrace();
		}
		renderJson(list);
	}

	@ActionKey("/user/delete")
	public void delete() {
		Map<String, Object> map = new HashMap<String, Object>();
		String id=getPara(0)==null?getPara("id"):getPara(0);
		try {
			Db.update("update users set isenable=0 where id=? ", id);
			Db.update("update album set isenable=0 where users_id=? ",id);
			Db.update("update reply set isenable=0 where users_id=? ", id);
			List<Album> albumids = new Album().find("select id from album where users_id=?", id);
			for (int i = 0; i < albumids.size(); i++) {
				Db.update("update video set isenable=0 where album_id=? ", albumids.get(i).get("id"));
			}
			map.put("flag", MessageUtil.SUCCESS.toString());
		} catch (Exception e) {
			map.put("flag", MessageUtil.FAILED.toString());
			e.printStackTrace();
		}
		renderJson(map);
	}

	@ActionKey("/user/active")
	public void active() {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Db.update("update users set active=1 where id=?", getPara("id"));
			map.put("flag", MessageUtil.SUCCESS.toString());
		} catch (Exception e) {
			map.put("flag", MessageUtil.FAILED.toString());
			e.printStackTrace();
		}
		renderJson(map);
	}
}
